# This Python file uses the following encoding: utf-8

#templates
from django.template import RequestContext
from django.shortcuts import render_to_response

from django.http import HttpResponseRedirect
from django.contrib.auth import logout

from django.contrib.auth.models import Group

from django.forms.forms import NON_FIELD_ERRORS

#auth
from django.contrib.auth.decorators import login_required
from utils.decorators import group_required
from utils import tools
from django.utils.datetime_safe import datetime
from django.db.models import Q
from utils.models import Preferencies
from django.forms.models import modelformset_factory

def logout_page(request):
    try:
        del request.session['impersonacio']
    except KeyError:
        pass
    
    logout(request)
    return HttpResponseRedirect('/')


def menu(request):
    #How do I make a variable available to all my templates?
    #http://readthedocs.org/docs/django/1.2.4/faq/usage.html#how-do-i-make-a-variable-available-to-all-my-templates
    
    if request.user.is_anonymous():
        from fp2cat.settings import LOGIN_URL
        return HttpResponseRedirect( LOGIN_URL )         
    else:
        #prenc impersonate user:
        (user, _) = tools.getImpersonateUser(request)    
        g, _ = Group.objects.get_or_create(name='lectors')
        if g in user.groups.all():
            return HttpResponseRedirect( 'correus/correuEdit/')
    
    return render_to_response(
            'main_page.html', 
            { },
            context_instance=RequestContext(request))    


def about(request):
    credentials = tools.getImpersonateUser(request) 
    (user, _ ) = credentials
    
    
    report = []
    taula = tools.classebuida()

    taula.titol = tools.classebuida()
    taula.titol.contingut = ''
    taula.titol.enllac = None

    taula.capceleres = []
    
    capcelera = tools.classebuida()
    capcelera.amplade = 150
    capcelera.contingut = u'Informació' 
    capcelera.enllac = None
    taula.capceleres.append(capcelera)

    capcelera = tools.classebuida()
    capcelera.amplade = 400
    capcelera.contingut = u''
    taula.capceleres.append(capcelera)

    
    taula.fileres = []
        
    filera = []
    
    #-by--------------------------------------------
    camp = tools.classebuida()
    camp.enllac = None
    camp.contingut = u'Llicència'
    camp.enllac = ''
    filera.append(camp)

    #-tip--------------------------------------------
    
    tip = u'''Desenvolupat per daniel herrera (ctrl.alt.d@gmail.com)
    '''
    camp = tools.classebuida()
    camp.enllac = ''
    camp.contingut = tip
    filera.append(camp)
    
    taula.fileres.append( filera )

    
    report.append(taula)
    
    return render_to_response(
                'report.html',
                    {'report': report,
                     'head': 'About' ,
                    },
                    context_instance=RequestContext(request))            


#-------------------------------------------------------------


@login_required
@group_required(['managers'])
def preferenciesEdit(request ):
    credentials = tools.getImpersonateUser(request) 
    (user, l4 ) = credentials
    
    if not l4:
        msgs = {}        
        msgs['errors'] = [ u'Només es pot accedir a aquesta pantalla en mode L4' ]
        msgs['url_next'] = r'/admin'
        return render_to_response(
                'resultat.html',
                    {'head': u'Modificació de paràmetres',
                     '''msgs''': msgs,
                    },
                    context_instance=RequestContext(request))        
        
    
    
    
    prm_model = Preferencies
    prm_url_next = '/utils/preferenciesEdit/'
    prm_head = "Manteniment de Preferències:"
    prm_can_delete = True

    extra = 0 if prm_model.objects.exists() else 1

    
    #missatge = u"MSG de campings!"
    formFac = modelformset_factory(prm_model, extra = extra, can_delete = prm_can_delete )
    
    if request.method == 'POST':
        formSet = formFac( request.POST )
        hi_ha_errors = False
        if formSet.is_valid():
            for form in formSet:
                if form not in formSet.deleted_forms and form.is_valid()  and form.cleaned_data:
                    form.save()
            for form in formSet.deleted_forms:
                instance = form.instance
                if instance.pk:
                    try:
                        instance.delete()
                    except Exception, e:                    
                        form._errors.setdefault(NON_FIELD_ERRORS, []).append(  'No puc esborrar aquesta dada, possiblement té altres dades associades.'  )
                        hi_ha_errors = True
            
            if not hi_ha_errors:
                return HttpResponseRedirect( prm_url_next )     
                          
    else:
        formSet = formFac( )

    for f in formSet:
        f.formSetDelimited = True        
        
    for f in formSet:
        f.fields['codi'].widget.attrs['class'] = 'curt'
        
    return render_to_response(
                'formset.html',
                    {'formset': formSet,
                     'head': prm_head,
                     'addMoreButton': True,
                     #'missatge' : missatge,
                    },
                    context_instance=RequestContext(request))




            
